<template>
  <div class="lunbo-edit">
    <el-tabs v-model="activeName">
      <el-tab-pane label="编辑" name="1">
        <div class="subhead">
          <p>{{ blockData.content }}</p>
        </div>
        <div class="poster">
          <div style="float:left;padding-left:20px;">
            <el-tabs v-model="active" class="sub-tabs" type="card">
              <template v-for="(item, index) in tabOptions">
                <el-tab-pane :name="item.code" :key="index">
                  <span slot="label">
                    <i class="el-icon-rank"/>
                    海报{{ item.code }}
                  </span>
                </el-tab-pane>
              </template>
            </el-tabs>
          </div>
          <div style="float:right">
            <el-button type="primary" @click="saveInfo">保存设置</el-button>
          </div>
        </div>
        <el-form
          v-if="currentActive"
          :model="currentActive"
          label-width="207px"
          style="margin-top:20px;"
        >
          <el-form-item label="是否开启">
            <el-radio-group v-model="currentActive.open">
              <el-radio :label="true">开启</el-radio>
              <el-radio :label="false">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="布局模式">
            <el-radio-group v-model="currentActive.layout">
              <el-radio label="widthLimit">限宽居中</el-radio>
              <el-radio label="planeSpread">平铺居中</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="编辑模式">
            <el-radio-group v-model="currentActive.mode">
              <el-radio label="template">图片模式</el-radio>
              <el-radio label="html">HTML模式</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="currentActive.mode === 'html'">
            <el-input :rows="22" type="textarea" style="width:700px"/>
          </el-form-item>
          <el-form-item :label="currentActive.mode === 'template'?'选择图片':''">
            <span v-if="currentActive.fileUrl">{{ currentActive.fileUrl.substring(21) }}</span>
            <el-upload
              :on-change="(file, FileList) => handleChange(file, FileList, currentActive)"
              :http-request="() => uploadFile(currentActive)"
              :show-file-list="false"
              class="upload-demo"
              action=""
            >
              <div v-if="currentActive.mode === 'template'" style="text-align: left">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">
                  [ 限宽居中 ] 图片推荐尺寸 宽：1140px，高：300px<br>
                  [ 平铺居中 ] 图片推荐尺寸 宽：1920px，高：450px<br>
                  建议所有海报都选择相同的 [ 布局模式 ]<br>
                  只能上传jpg/png文件，且不超过500kb
                </div>
                <img v-if="currentActive.fileUrl" :src="currentActive.fileUrl" alt class="img">
              </div>
              <el-button v-if="currentActive.mode === 'html'">上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item v-if="currentActive.mode === 'template'" label="背景色填充">
            <el-color-picker v-model="currentActive.backgroundColor"/>
          </el-form-item>
          <el-form-item v-if="currentActive.mode === 'template'" label="海报链接地址">
            <el-input v-model="currentActive.link" style="width:400px;" placeholder="http://"/>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="历史记录" name="2">
        <div v-if="activeName === '2'">
          <el-table :data="tableData" style="width: 100%" border>
            <el-table-column prop="createTimeStr" label="修改时间" min-width="20" align="center"/>
            <el-table-column prop="userName" label="修改用户" min-width="10" align="center"/>
            <el-table-column prop="manage" label="操作" min-width="20" align="center">
              <template slot-scope="scope">
                <!--<el-button type="primary" @click="preview(scope.row)">预览</el-button>-->
                <el-button type="success" @click="recovery(scope.row)">恢复此内容</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import Sortable from 'sortablejs'
  import { getBlockHistory, getBlockTemplate, recoveryBlockTemplate, saveBlockTemplate } from '@/api/operate/block' // 数据接口
  import { upLoadFile } from '@/api/upLoadFile'
  import { getTenantId, getUserId, getUserName } from '@/utils/auth'

  export default {
    components: {},
    data() {
      return {
        blockData: {},
        activeName: '1',
        active: '1',
        templateData: '1,2,3,4,5',
        tabList: {
          1: {
            blockId: '',
            open: true,
            layout: 'widthLimit',
            mode: 'template',
            backgroundColor: '#1d75ed',
            link: '',
            file: '',
            fileId: '',
            fileUrl: ''
          },
          2: {
            blockId: '',
            open: true,
            layout: 'widthLimit',
            mode: 'template',
            backgroundColor: '#1d75ed',
            link: '',
            file: '',
            fileId: '',
            fileUrl: ''
          },
          3: {
            blockId: '',
            open: false,
            layout: 'widthLimit',
            mode: 'template',
            backgroundColor: '#1d75ed',
            link: '',
            file: '',
            fileId: '',
            fileUrl: ''
          },
          4: {
            blockId: '',
            open: false,
            layout: 'widthLimit',
            mode: 'template',
            backgroundColor: '#1d75ed',
            link: '',
            file: '',
            fileId: '',
            fileUrl: ''
          },
          5: {
            blockId: '',
            open: false,
            layout: 'widthLimit',
            mode: 'template',
            backgroundColor: '#1d75ed',
            link: '',
            file: '',
            fileId: '',
            fileUrl: ''
          }
        },
        tabOptions: [
          {
            code: '1'
          },
          {
            code: '2'
          },
          {
            code: '3'
          },
          {
            code: '4'
          },
          {
            code: '5'
          }
        ],
        saveData: [],
        tableData: []
      }
    },
    computed: {
      currentActive() {
        return this.tabList[this.active]
      }
    },
    created() {
      this.getInfoData()
      this.getBlockTemplate()
      this.getHistoryData()
    },
    mounted() {
      this.setSort()
    },
    methods: {
      setSort() {
        // 拖拽排序
        const _this = this
        const el = document.querySelectorAll('.sub-tabs .el-tabs__nav')[0]
        Sortable.create(el, {
          onEnd(evt) {
            let templateData = ''
            evt.to.childNodes.forEach(childNode => {
              templateData += childNode.id.substring(childNode.id.length - 1) + ','
            })
            templateData = templateData.substring(0, templateData.length - 1)
            _this.templateData = templateData
          }
        })
      },
      getBlockTemplate() {
        getBlockTemplate(this.blockData.id, getTenantId()).then(response => {
          response.data.items.forEach((item, index) => {
            this.tabList[index + 1] = item
          })
          if (response.data.items.length !== 0) {
            const orders = response.data.items[0].templateData.split(',')
            orders.forEach((order, index) => {
              this.tabOptions[index].code = order
            })
            this.active = this.tabOptions[0].code
          }
        })
      },
      getInfoData() {
        if (this.$route.params) {
          this.blockData = this.$route.params
          for (const key in this.tabList) {
            this.tabList[key].blockId = this.blockData.id
          }
        }
      },
      handleChange(file) {
        this.tabList[this.active].file = file.raw
      },
      uploadFile() {
        const fileForm = new FormData()
        fileForm.append('name', this.tabList[this.active].file.name)
        fileForm.append('uid', this.tabList[this.active].file.uid)
        fileForm.append('file', this.tabList[this.active].file)
        upLoadFile(fileForm).then(response => {
          this.tabList[this.active].fileId = response.data.id
          this.tabList[this.active].fileUrl = response.data.url
        })
      },
      saveInfo() {
        this.tabOptions.map(tab => {
          this.tabList[tab.code].code = tab.code
          this.tabList[tab.code].templateData = this.templateData
        })
        for (const index in this.tabList) {
          this.tabList[index].tenantId = getTenantId()
          this.tabList[index].userId = getUserId()
          this.tabList[index].userName = getUserName()
          delete this.tabList[index].file
        }

        saveBlockTemplate(this.tabList).then(() => {
          this.$notify({
            title: '成功',
            message: '提交成功！',
            type: 'success',
            duration: 2000
          })
          this.$router.push({ name: 'Edit' })
        })
      },
      getHistoryData() {
        getBlockHistory(this.blockData.id, getTenantId()).then(response => {
          response.data.items.map(item => {
            if (item.createTime) item.createTimeStr = new Date(item.createTime).toLocaleString().replace(/[\u4e00-\u9fa5]/g, '')
          })
          this.tableData = response.data.items
        })
      },
      // 预览
      preview(row) {
      },
      // 恢复
      recovery(row) {
        recoveryBlockTemplate(row).then(() => {
          this.$notify({
            title: '成功',
            message: '重置成功！',
            type: 'success',
            duration: 2000
          })
          this.$router.push({ name: 'Edit' })
        })
      }
    }
  }
</script>

<style lang="scss">
  .lunbo-edit {
    padding: 0 20px;

    .upload-demo {
      width: 300px;

      .img {
        width: auto;
        height: 100px;
      }
    }

    .el-tabs__item {
      font-size: 16px;
    }

    .subhead {
      background-color: #f8f8f8;
      width: 100%;
      height: 40px;
      line-height: 40px;

      p {
        margin: 0;
        box-sizing: border-box;
        padding-left: 20px;
      }

      .submmit {
        float: right;
      }
    }

    .poster {
      background-color: #e6eaee;
      width: 100%;
      height: 70px;
      line-height: 70px;
      padding-right: 20px;

      .el-tabs__item.is-active {
        background: #00adff;
        border-radius: 4px;
        color: #fff;
      }
    }
  }
</style>
